package com.shop.shopserver.handler;


import com.alibaba.fastjson.JSON;
import com.shop.shopcommon.result.Result;
import com.shop.shoppojo.vo.UserLoginSuccessVO;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.shop.shopcommon.constant.MessageConstant.LOGIN_FAIL;
/**
 * 登录失败处理器
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 登录失败处理逻辑，返回 JSON 响应
        response.setContentType("application/json;charset=UTF-8");
        // 调用 Result 类的 error 方法创建结果对象
        Result<UserLoginSuccessVO> result = Result.error(LOGIN_FAIL);
        // 将结果对象转换为 JSON 字符串，并写入响应体中
        response.getWriter().write(JSON.toJSONString(result));
    }
}